<template>
    <div>


        <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick" @tab-change="handleChange">
            <el-tab-pane label="已安装" name="first">
                <el-card class="!border-none mb-4" shadow="never">
                    <el-form class="mb-[-16px]" :model="queryParams" inline>
                        <el-form-item label="应用名称" prop="name">
                            <el-input class="w-[280px]" v-model="queryParams.name" clearable placeholder="请输入应用名称" />
                        </el-form-item>
                        <el-form-item label="安装时间" prop="create_time">
                            <el-input class="w-[280px]" v-model="queryParams.create_time" clearable placeholder="请输入安装时间" />
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="getLists">查询</el-button>
                            <el-button @click="resetParams">重置</el-button>
                        </el-form-item>
                    </el-form>
                </el-card>
                <el-card class="!border-none mb-4" shadow="never">
                    <el-alert description="温馨提示：更新后需要按Ctrl+F5强制刷新页面后再使用" type="info" :closable="false" />
                </el-card>
                <el-card class="!border-none" v-loading="pager.loading" shadow="never">
                    <div class="mt-4">
                        <el-table :data="allAppListFormat">
                            <!-- <el-table-column type="selection" width="55" /> -->
                            <el-table-column type="expand">
                                <template #default="props">
                                    <div m="4">
                                        <el-table :data="props.row.plugs" :show-header="false">
                                            <el-table-column min-width="12">

                                            </el-table-column>
                                            <el-table-column label="插件图标" min-width="100">
                                                <template #default="{ row }">
                                                    <el-avatar :src="row.app_icon" :size="50" />
                                                </template>
                                            </el-table-column>
                                            <el-table-column label="插件名称" prop="name" show-overflow-tooltip />
                                            <el-table-column label="插件版本号" prop="version_no" show-overflow-tooltip>
                                                <template #default="{ row }">
                                                    <div style="display:flex;">
                                                        {{ row.version_no }}
                                                        <div v-if="row.is_newversion == 1" style="margin-left: 10px;">
                                                            <router-link :to="{
                                                                path: getRoutePath(
                                                                    'application/appDetail'
                                                                ),
                                                                query: {
                                                                    app: row.app,
                                                                    title: 1,
                                                                },
                                                            }">
                                                                <el-button type="success" size="small">发现新版本</el-button>
                                                            </router-link>
                                                        </div>
                                                    </div>
                                                </template>
                                            </el-table-column>
                                            <el-table-column label="操作" min-width="120" fixed="right">
                                                <template #default="{ row }">
                                                    <el-button type="primary" link>
                                                        <router-link :to="{
                                                            path: getRoutePath(
                                                                'application/appDetail'
                                                            ),
                                                            query: {
                                                                app: row.app,
                                                            },
                                                        }">
                                                            查看详情
                                                        </router-link>
                                                    </el-button>
                                                    <el-button type="primary" link>
                                                        <router-link :to="{
                                                            path: getRoutePath(
                                                                'application/appDetail'
                                                            ),
                                                            query: {
                                                                app: row.app,
                                                                title: 1
                                                            },
                                                        }">
                                                            检查更新
                                                        </router-link>
                                                    </el-button>
                                                </template>
                                            </el-table-column>
                                        </el-table>
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column label="图标" min-width="100">
                                <template #default="{ row }">
                                    <el-avatar :src="row.app_icon" :size="50" />
                                </template>
                            </el-table-column>
                            <el-table-column label="应用名称" prop="name" show-overflow-tooltip />
                            <el-table-column label="版本号" prop="version_no" show-overflow-tooltip>
                                <template #default="{ row }">
                                    <div style="display:flex;">
                                        {{ row.version_no }}
                                        <div v-if="row.is_newversion == 1" style="margin-left: 10px;">
                                            <router-link :to="{
                                                path: getRoutePath(
                                                    'application/appDetail'
                                                ),
                                                query: {
                                                    app: row.app,
                                                    title: 1,
                                                },
                                            }">
                                                <el-button type="success" size="small">发现新版本</el-button>
                                            </router-link>
                                        </div>
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column label="操作" min-width="120" fixed="right">
                                <template #default="{ row }">
                                    <el-button type="primary" link
                                        @click="deleteHandle(row.app_icon, row.name, row.version_no, row.app, row)">
                                        卸载应用
                                    </el-button>
                                    <el-button type="primary" link @click="viewDetails(row)">
                                        <router-link :to="{
                                            path: getRoutePath(
                                                'application/appDetail'
                                            ),
                                            query: {
                                                app: row.app,
                                            },
                                        }">
                                            查看详情
                                        </router-link>
                                    </el-button>
                                    <el-button type="primary" link @click="viewDetails(row)">
                                        <router-link :to="{
                                            path: getRoutePath(
                                                'application/appDetail'
                                            ),
                                            query: {
                                                app: row.app,
                                                title: 1,
                                            },
                                        }">
                                            检查更新
                                        </router-link>
                                    </el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </el-card>
            </el-tab-pane>
            <el-tab-pane label="未安装" name="second"><el-card class="!border-none" v-loading="pager.loading" shadow="never">
                    <el-card class="!border-none mb-4" shadow="never">
                        <el-form class="mb-[-16px]" :model="queryParams" inline>
                            <el-form-item label="应用名称" prop="name">
                                <el-input class="w-[280px]" v-model="queryParams.name" clearable placeholder="请输入应用名称" />
                            </el-form-item>
                            <el-form-item label="安装时间" prop="create_time">
                                <el-input class="w-[280px]" v-model="queryParams.create_time" clearable
                                    placeholder="请输入安装时间" />
                            </el-form-item>
                            <el-form-item label="卸载时间" prop="uninstall_time">
                                <el-input class="w-[280px]" v-model="queryParams.uninstall_time" clearable
                                    placeholder="请输入卸载时间" />
                            </el-form-item>
                            <el-form-item>
                                <el-button type="primary" @click="getLists">查询</el-button>
                                <el-button @click="resetParams">重置</el-button>
                            </el-form-item>
                        </el-form>
                    </el-card>
                    <div class="mt-4">
                        <el-table :data="appListSecond">
                            <el-table-column label="图标" min-width="100">
                                <template #default="{ row }">
                                    <el-avatar :src="row.app_icon" :size="50" />
                                </template>
                            </el-table-column>
                            <el-table-column label="应用名称" prop="name" show-overflow-tooltip />
                            <el-table-column label="版本号" prop="version_no" show-overflow-tooltip />
                            <el-table-column label="操作" width="120" fixed="right">
                                <template #default="{ row }">
                                    <el-button type="primary" link @click="install(row.app)">
                                        安装
                                    </el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </el-card></el-tab-pane>
            <el-tab-pane label="未安装插件" name="third"><el-card class="!border-none" v-loading="pager.loading" shadow="never">
                    <el-card class="!border-none mb-4" shadow="never">
                        <el-form class="mb-[-16px]" :model="queryParams" inline>
                            <el-form-item label="应用名称" prop="name">
                                <el-input class="w-[280px]" v-model="queryParams.name" clearable placeholder="请输入应用名称" />
                            </el-form-item>
                            <el-form-item label="安装时间" prop="create_time">
                                <el-input class="w-[280px]" v-model="queryParams.create_time" clearable
                                    placeholder="请输入安装时间" />
                            </el-form-item>
                            <el-form-item label="卸载时间" prop="uninstall_time">
                                <el-input class="w-[280px]" v-model="queryParams.uninstall_time" clearable
                                    placeholder="请输入卸载时间" />
                            </el-form-item>
                            <el-form-item>
                                <el-button type="primary" @click="getLists">查询</el-button>
                                <el-button @click="resetParams">重置</el-button>
                            </el-form-item>
                        </el-form>
                    </el-card>
                    <div class="mt-4">
                        <el-table :data="appListThird">
                            <el-table-column label="图标" min-width="100">
                                <template #default="{ row }">
                                    <el-avatar :src="row.app_icon" :size="50" />
                                </template>
                            </el-table-column>
                            <el-table-column label="应用名称" prop="name" show-overflow-tooltip />
                            <el-table-column label="版本号" prop="version_no" show-overflow-tooltip />
                            <el-table-column label="操作" width="120" fixed="right">
                                <template #default="{ row }">
                                    <el-button type="primary" link @click="installPlugin(row.app)">
                                        安装
                                    </el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </el-card>
            </el-tab-pane>
            <el-tab-pane label="回收站" name="fourth">
                <el-card class="!border-none mb-4" shadow="never">
                    <el-form class="mb-[-16px]" :model="formData" inline>
                        <el-form-item label="应用名称" prop="name">
                            <el-input class="w-[280px]" v-model="name" clearable placeholder="请输入应用名称" />
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="getUnloadapp">查询</el-button>
                        </el-form-item>
                    </el-form>
                </el-card>
                <el-card class="!border-none" v-loading="pager.loading" shadow="never">
                    <div class="mt-4">
                        <el-table :data="formData">
                            <el-table-column label="应用图标" min-width="100">
                                <template #default="{ row }">
                                    <el-avatar :src="row.icon" :size="50" />
                                </template>
                            </el-table-column>
                            <el-table-column label="应用名称" prop="name" show-overflow-tooltip />
                            <el-table-column label="版本号" prop="version_no" show-overflow-tooltip />
                            <el-table-column label="操作" width="200" fixed="right">
                                <template #default="{ row }">
                                    <el-button type="primary" link @click="Restore(row.id)">
                                        恢复应用
                                    </el-button>
                                    <el-button type="primary" link @click="deleteHandler(row.id)">
                                        彻底卸载
                                    </el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </el-card>
            </el-tab-pane>
            <el-tab-pane label="安装本地文件" name="fifth">
                <el-card class="!border-none mb-4" shadow="never">
                    <el-form-item label="上传验证文件" style="margin-top: 10px">
                        <div class="w-80" style="display: flex;width: 500px;">
                            <el-upload ref="uploadRef" class="upload-demo" :action="uploadAction" :headers="uploadToken"
                                :on-success="successHandle" :limit="1" :on-error="errorHandle" style="width: 500px;">
                                <el-button>上传并安装</el-button>
                            </el-upload>
                        </div>
                        <el-alert description="上传压缩包文件" type="info" :closable="false" />
                    </el-form-item>
                </el-card>
            </el-tab-pane>
        </el-tabs>

        <edit-popup v-if="showEdit" ref="editRef" :dict-data="dictData" @success="getLists" @close="showEdit = false" />
    </div>
</template>

<script lang="ts" setup name="managementEdit">
import { usePaging } from "@/hooks/usePaging";
import { useDictData } from "@/hooks/useDictOptions";
import {
    apiInstallappLists,
    apiInstallappDelete,
    getAppPlugsList,
    installAppPlugs,
    installLocationApp
} from "@/api/installapp";
import { getToken } from "@/utils/auth";
import type { UploadProps } from "element-plus";
import { getAppList, installApp, unloadappDelete, unloadappLists, unloadappRestore, unloadappTrueDelete, newInstallapp } from "@/api/cloudupdate";
import { timeFormat } from "@/utils/util";
import feedback from "@/utils/feedback";
import cache from "@/utils/cache";
import EditPopup from "./managementedit.vue";
import { getRoutePath } from "@/router";

import { ElLoading, ElMessageBox } from "element-plus";

const getActiveName = cache.get("activeName");
const activeName = ref(getActiveName ? getActiveName : "first");
const router = useRouter()
const allAppList = ref<any[]>([]);
const allAppListFormat = ref<any[]>([]);
const appListSecond = ref<any[]>([]);
const appListThird = ref<any[]>([]);
const editRef = shallowRef<InstanceType<typeof EditPopup>>();
// 是否显示编辑框
const showEdit = ref(false);
const successHandle: UploadProps["onSuccess"] = (response, uploadFile) => {
    feedback.msgSuccess(response.msg)
    upload(response.data.app, response.data.url)
};
interface uploadTokenObj {
    token: string;
}
const uploadToken = ref<uploadTokenObj>({
    token: getToken(),
});
const errorHandle = async (err: any, file: any, fileList: any) => {
    // await feedback.msgError("上传文件失败")
    console.log(err, "Err")
    console.log(file, "file")
    console.log(fileList, "fileList")
}
const hostname = location.hostname;
// const uploadAction = 'https://test.xiaojiangy.cn/adminapi/appTemp/file';
const uploadAction = '/adminapi/setting.wechat_open/upload';
// 查询条件
const queryParams = reactive({
    name: "",
    create_time: "",
    uninstall_time: "",
});
const upload = async (appListSecond: any, fileurl: any) => {
    await installLocationApp({ app: appListSecond, fileurl: fileurl })
}
// 选中数据
const selectData = ref<any[]>([]);

// 表格选择后回调事件
const handleSelectionChange = (val: any[]) => {
    selectData.value = val.map(({ id }) => id);
};
const pager = reactive({
    page: 1,
    size: 999,
    loading: false,
    count: 0,
    lists: [] as any[],
});

// 获取字典数据
const { dictData } = useDictData("");

// 分页相关
// const { pager, getLists, resetParams, resetPage } = usePaging({
//     fetchFun: apiInstallappLists,
//     params: queryParams,
// });
const resetPage = () => {
    resetPage;
};
const not = ref();
// 添加
const handleAdd = async () => {
    showEdit.value = true;
    await nextTick();
    editRef.value?.open("add");
};

// 编辑
const handleEdit = async (data: any) => {
    showEdit.value = true;
    await nextTick();
    editRef.value?.open("edit");
    editRef.value?.setFormData(data);
};
const open = async (id: any) => {

}
// 删除
const handleDelete = async (id: number | any[]) => {
    await feedback.confirm("确定要删除？");
    await apiInstallappDelete({ id });
    getLists();
};

onMounted(async () => {
    getData();
    getUnloadapp()
});
const getData = async () => {
    await getLists(); //已安装的
    getGetAppList(); //所有的
    getPlugins(); // 未安装插件
    
    const currentProtocol = window.location.protocol;
    console.log(currentProtocol)
    not.value = currentProtocol
};

const getPlugins = async () => {
    await getAppPlugsList(queryParams).then((res) => {
        appListThird.value = res.filter((v: any) => {
            // return allAppList.value.every((e: any) => e.app != v.app);
            return v.is_install == 0 ? 1 : 0;
        });
        allAppList.value.forEach((element: any) => {
            res.forEach((i: any) => {
                if (element.app == i.app) {
                    element.last_version_no = i.version_no;
                    element.app_icon = i.app_icon;
                    console.log(element);
                }
            });
        });
        allAppListFormat.value = allAppList.value;
    });
};

const getLists = async () => {
    await apiInstallappLists(queryParams)
        .then((res) => {
            allAppList.value = []
            for (var i = 0; i < res.lists.length; i++) {
                if (res.lists[i].uninstall_time == 0) {
                    allAppList.value.push(res.lists[i])
                }
            }
            // allAppList.value = res.lists;
        })
        .catch((ret) => { });
};
const getGetAppList = async () => {
    await getAppList(queryParams)
        .then((res) => {
            appListSecond.value = res.filter((v: any) => {
                // return allAppList.value.every((e: any) => e.app != v.app);
                return v.is_install == 0 ? 1 : 0;
            });
            allAppList.value.forEach((element: any) => {
                res.forEach((i: any) => {
                    if (element.app == i.app) {
                        element.last_version_no = i.version_no;
                        element.app_icon = i.app_icon;
                        console.log(element);
                    }
                });
            });
            allAppListFormat.value = allAppList.value;
        })
        .catch((ret) => { });
};
const resetParams = () => { };
const handleClick = (vv: any) => { };
const handleChange = (vv: any) => {
    cache.set("activeName", vv);
};
//查看详情
const viewDetails = (row: any) => {
    console.log("row", row);
};
const current = ref(0)
const install = (app: string) => {
    ElMessageBox.confirm("确认安装应用？", "安装应用提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        // if you want to disable its autofocus
        // autofocus: false,
    })
        .then(() => {
            const loading = ElLoading.service({
                lock: true,
                text: "安装中...",
                background: "rgba(0, 0, 0, 0.7)",
            });
            newInstallapp({ app: app, currstep: 0 })
                .then((res) => {
                    newInstallapp({ app: app, currstep: 1 })
                        .then((res) => {
                            loading.close();
                            const loadings = ElLoading.service({
                                lock: true,
                                text: "更新到最新版中...",
                                background: "rgba(0, 0, 0, 0.7)",
                            });
                            newInstallapp({ app: app, currstep: 2 })
                                .then((res) => {
                                    loadings.close();
                                    getData();
                                })
                                .catch((ret) => {
                                    loadings.close();
                                    getData();
                                });
                        })
                        .catch((ret) => {
                            loading.close();
                            getData();
                        });
                })
                .catch((ret) => {
                    loading.close();
                });
        })
        .catch(() => { });
};

const installPlugin = (app: string) => {
    ElMessageBox.confirm("确认安装应用？", "安装应用提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        // if you want to disable its autofocus
        // autofocus: false,
    })
        .then(() => {
            const loading = ElLoading.service({
                lock: true,
                text: "安装中...",
                background: "rgba(0, 0, 0, 0.7)",
            });
            newInstallapp({ app: app, currstep: 0 })
                .then((res) => {
                    newInstallapp({ app: app, currstep: 1 })
                        .then((res) => {
                            loading.close();
                            const loadings = ElLoading.service({
                                lock: true,
                                text: "更新到最新版中...",
                                background: "rgba(0, 0, 0, 0.7)",
                            });
                            newInstallapp({ app: app, currstep: 2 })
                                .then((res) => {
                                    loadings.close();
                                    getData();
                                })
                                .catch((ret) => {
                                    loadings.close();
                                    getData();
                                });
                        })
                        .catch((ret) => {
                            loading.close();
                            getData();
                        });
                })
                .catch((ret) => {
                    loading.close();
                });
        })
        .catch(() => { });
};




// 卸载
const deleteHandle = async (icon: string, name: string, version: string, app: string, row: string) => {
    await feedback.confirm("确定要卸载？");
    await unloadappDelete({ icon: icon, name: name, app: app, version_no: version })
    getData();
    getUnloadapp()
}
const formData = ref([
    {
        app: "",
        create_time: "",
        icon: "",
        id: "",
        name: "",
        version_no: ""
    }
])
const name = ref("")
const getUnloadapp = async () => {
    const results = await unloadappLists({ name: name.value })
    formData.value = results.lists
}

const Restore = async (id: number) => {
    await unloadappRestore({ id: id })
    getData();
    getUnloadapp()
}
const deleteHandler = async (id: number) => {
    await feedback.confirm("确定要卸载？");
    await unloadappTrueDelete({ id: id })
    getData();
    getUnloadapp()
}
    // getLists();
</script>

